﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace 使用XmlDocument
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void btnReadAll_Click(object sender, EventArgs e)
        {
            List<BookModel> bookModeList = new List<BookModel>();
            // 创建XmlDDocument对象，并装入xml文件
            XmlDocument xmlDoc = new XmlDocument();

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;//忽略文档里面的注释
            XmlReader reader = XmlReader.Create(@"..\..\Book.xml", settings);
            xmlDoc.Load(reader);

            //xn 代表一个结点
            //xn.Name;//这个结点的名称
            //xn.Value;//这个结点的值
            //xn.ChildNodes;//这个结点的所有子结点
            //xn.ParentNode;//这个结点的父结点

            // 得到根节点bookstore
            XmlNode xn = xmlDoc.SelectSingleNode("bookstore");


            // 得到根节点的所有子节点
            XmlNodeList xnl = xn.ChildNodes;

            foreach (XmlNode xn1 in xnl)
            {
                BookModel bookModel = new BookModel();
                // 将节点转换为元素，便于得到节点的属性值
                XmlElement xe = (XmlElement)xn1;
                // 得到Type和ISBN两个属性的属性值
                bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
                bookModel.BookType = xe.GetAttribute("Type").ToString();
                // 得到Book节点的所有子节点
                XmlNodeList xnl0 = xe.ChildNodes;
                bookModel.BookName=xnl0.Item(0).InnerText;
                bookModel.BookAuthor=xnl0.Item(1).InnerText;
                bookModel.BookPrice=Convert.ToDouble(xnl0.Item(2).InnerText);
                bookModeList.Add(bookModel);
            }
            reader.Close();
            dgvBookInfo.DataSource = bookModeList;

        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.dgvBookInfo.RowsDefaultCellStyle.BackColor = Color.Bisque;
            this.dgvBookInfo.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
        }

        private void dgvBookInfo_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //显示行号
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgvBookInfo.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgvBookInfo.RowHeadersDefaultCellStyle.Font, rectangle,
                dgvBookInfo.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

            }
            catch { }
        }

        private void btnAddOne_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            //doc.LoadXml("<bookstore></bookstore>");//用这句话,会把以前的数据全部覆盖掉,只有你增加的数据
            doc.Load(@"..\..\Book.xml");
            XmlNode root = doc.SelectSingleNode("bookstore");


            XmlElement xelKey = doc.CreateElement("book");

            XmlAttribute xelType = doc.CreateAttribute("Type");
            xelType.InnerText = "adfdsf";
            xelKey.SetAttributeNode(xelType);

            XmlAttribute xelISBN = doc.CreateAttribute("ISBN");
            xelISBN.InnerText = "11111111";
            xelKey.SetAttributeNode(xelISBN);

            XmlElement xelTitle = doc.CreateElement("title");
            xelTitle.InnerText = "dadsa";
            xelKey.AppendChild(xelTitle);

            XmlElement xelAuthor = doc.CreateElement("author");
            xelAuthor.InnerText = "dfdsa";
            xelKey.AppendChild(xelAuthor);

            XmlElement xelPrice = doc.CreateElement("price");
            xelPrice.InnerText = "35.00";
            xelKey.AppendChild(xelPrice);


            root.AppendChild(xelKey);

            doc.Save(@"..\..\Book.xml");
            MessageBox.Show("插入成功！");
            btnReadAll_Click(sender, e);

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvBookInfo.CurrentRow != null)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(@"..\..\Book.xml");
                XmlElement xe = xmlDoc.DocumentElement; // DocumentElement 获取xml文档对象的根XmlElement.
                string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
                XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath);  //selectSingleNode 根据XPath表达式,获得符合条件的第一个节点.
                selectXe.ParentNode.RemoveChild(selectXe);
                xmlDoc.Save(@"..\..\Book.xml");
                MessageBox.Show("删除成功！");
                btnReadAll_Click(sender, e);

//                 XmlNodeList someBooks = root.SelectNodes("/books/book[price<10]");
//              Console.Out.WriteLine("---  再将所有价格低于10的书删除  ---");
//             Console.Out.WriteLine("---  符合条件的书有　"   someBooks.Count   "本。  ---");
//
//               for (int i = 0; i < someBooks.Count; i ++ )
//               {
//                   someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));
//                }

            }

        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (dgvBookInfo.CurrentRow != null)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(@"..\..\Book.xml");
                XmlElement xe = xmlDoc.DocumentElement; // DocumentElement 获取xml文档对象的根XmlElement.
                string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
                XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath);  //selectSingleNode 根据XPath表达式,获得符合条件的第一个节点.
                selectXe.SetAttribute("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());//也可以通过SetAttribute来增加一个属性
                selectXe.GetElementsByTagName("title").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[2].Value.ToString();
                selectXe.GetElementsByTagName("author").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[3].Value.ToString();
                selectXe.GetElementsByTagName("price").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[4].Value.ToString();
                xmlDoc.Save(@"..\..\Book.xml");
                MessageBox.Show("修改成功！");
                btnReadAll_Click(sender,e);
            }
        }
    }
}
